import time
from time import sleep
from framework.Function.ModbusBasicFunction.function import *
from utils.Exception.ExecutionException import *
import threading
import queue

#stop_event 决定要不要停止线程执行 跳出循环
def system_error_information_monitoring(stop_event, error_queue):
    try:
        global string
        string = []
        while not stop_event.is_set():
            if read_reg_IntOrBool(120) != 0:
                i = 121
                while read_reg_IntOrBool(i) != 0 and i <= 139:
                    read = read_reg_IntOrBool(i)
                    if 0 <= read <= 999:
                        string.append(f"系统相关错误 错误ID:{read}")
                    elif 1000 <= read <= 1999:
                        string.append(f"小车相关错误 错误ID:{read}")
                    elif 2000 <= read <= 2999:
                        string.append(f"摆渡段马达/普通马达错误 错误ID:{read}")
                    elif 3000 <= read <= 3999:
                        string.append(f"驱动单元错误 错误ID:{read}")
                    else:
                        string.append(f"系统错误 错误ID:{read}")
                    i += 2
                break
            sleep(0.1)  # 每100ms检测一次
        if string:
            raise ExecutionException(string)
    except ExecutionException as e:
        error_queue.put(e)  # 将异常传递到队列
    except Exception as e:
        error_queue.put(e)


#该线程用于读取小车到位信号
def car_position_signal(stop_event, error_queue, process_num=1):
    try:
        address = 3019 + ((process_num - 1) * 70)
        while not stop_event.is_set():
            if read_reg_IntOrBool(address) == 1:
                raise ExecutionException("测试未通过:读取到不应该出现的小车到位信号")

    except ExecutionException as e:
        error_queue.put(e)  # 将异常传递到队列
    except Exception as e:
        error_queue.put(e)

#该线程用于监控单小车区域内小车数量
def single_car_area_car_count_monitor(stop_event, error_queue):
    try:
        car_num = read_car_num()
        start_pos = read_reg_float(1065)
        end_pos =  read_reg_float(1067)
        while not stop_event.is_set():
            i = 1
            count = 0
            while i <= car_num:
                if start_pos-20.0 <= read_car_position(i) >= end_pos:
                    count += 1
                i += 1
            if count >= 2:
                raise ExecutionException(f"测试未通过:单小车区域出现{count}辆小车")

    except ExecutionException as e:
        error_queue.put(e)  # 将异常传递到队列
    except Exception as e:
        error_queue.put(e)
